﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EmptyProject
{
    /// <summary>
    /// 从指定网址获取配置信息：
    /// Configer.Instance.Get("QrPayServerAddress")
    /// 
    /// serverInfo.txt：
    /// QrPayServerAddress(127.0.0.1:7002)QrPayServerAddress
    /// ApplicationTest(127.0.0.1:7001)ApplicationTest
    /// </summary>
    public class Configer
    {
        public static Configer Instance = new Configer();

        private string url = "";    // 配置文件文件网址

        public Configer(string url = "https://scimence.gitee.io/config/files/config.txt")
        {
            this.url = url;
        }

        /// <summary>
        /// 获取key对应的配置信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string Get(string key)
        {
            if (url == null || url.Equals("")) return "";
            if (key == null || key.Equals("")) return "";

            string value = getWebData(url, key);
            return value;
        }

        //---------

        //从给定的网址中获取数据
        private static string getWebData(string url, string key)
        {
            string data = getWebData(url);
            string value = getNodeData(data, key, false);
            return value;
        }

        //从给定的网址中获取数据
        private static string getWebData(string url)
        {
            try
            {
                System.Net.WebClient client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;
                string data = client.DownloadString(url);
                return data;
            }
            catch (Exception) { return ""; }
        }

        // 从自定义格式的数据data中，获取nodeName对应的节点数据
        //p>scimence(&#x000A;NeedToRegister(false)NeedToRegister&#x000A;RegisterPrice(1)RegisterPrice&#x000A;)scimence</p>&#x000A;</div>
        // NeedToRegister(false)&#x000A;RegisterPrice(1)   finalNode的数据格式
        private static string getNodeData(string data, string nodeName, bool finalNode)
        {
            try
            {
                string S = nodeName + "(", E = ")" + (finalNode ? "" : nodeName);
                int indexS = data.IndexOf(S) + S.Length;
                int indexE = data.IndexOf(E, indexS);

                return data.Substring(indexS, indexE - indexS);
            }
            catch (Exception) { return data; }
        }
    }
}
